﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Web;
using System.Xml.Linq;
using System.IO;

namespace web.component
{
    public class Uconfig
    {
        public static string LoadNodeConfigSite( string nodeKey,string path)
        {
            try
            {
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(path);
                XmlNode node = xmldoc.SelectSingleNode("configuration/appSettings/add[@key = '" + nodeKey + "']");
                if (node != null)
                {
                    XmlNode valueAttribute = node.Attributes.GetNamedItem("value");
                    if (valueAttribute != null)
                    {
                        //txtTime.Text = (int.Parse(valueAttribute.Value.ToString()) / 60000).ToString();
                        return valueAttribute.Value.ToString();
                    }
                    else
                        return "";
                }
                else
                    return "";
            }
            catch (Exception ex) {
                return ex.ToString();
            }
        }

        public bool CheckKeyConfigSite(string Keys, string path)
        {
            try
            {
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(path);
                XmlNode node = xmldoc.SelectSingleNode("configuration/appSettings/add[@key = '" + Keys + "']");
                //XmlNode valueAttribute = node.Attributes.GetNamedItem("value");
                // save file config
                if (node != null)
                {
                    return true;
                }
                else
                    return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void Update(string Values, string Keys, string path)
        {
            try
            {
                //update the config file
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(path);
                XmlNode node = xmldoc.SelectSingleNode("configuration/appSettings/add[@key = '" + Keys + "']");
                XmlNode valueAttribute = node.Attributes.GetNamedItem("value");
                // save file config
                if (valueAttribute != null)
                {
                    valueAttribute.InnerXml = Values;
                    xmldoc.Save(path);
                }

                //update the cached setting
                //System.Configuration.ConfigurationManager.AppSettings.Set("" + Keys + "", Values);
                //LoadGridView(int.Parse(dropRows.SelectedValue));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void CreateNode( string Values, string Keys, string path)
        {
            try
            {
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(path);
                XmlNode appSettingNode = xmldoc.SelectSingleNode("configuration/appSettings");

                //Create a new node
                XmlElement newkey = xmldoc.CreateElement("add");
                newkey.SetAttribute("key", Keys);
                newkey.SetAttribute("value", Values);

                appSettingNode.AppendChild(newkey);

                xmldoc.Save(path);
                //LoadGridView(int.Parse(dropRows.SelectedValue));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// tao file config tu Dictionary obj
        /// </summary>
        /// <param name="dict"></param>
        /// <param name="config_file"></param>
        public static void CreateConfigFile(Dictionary<string, string> dict, string config_file)
        {
            try
            {
                var xmlDoc = new XDocument(new XDeclaration("1.0", "utf-8", "true"),
                                                       new XComment(
                                                           string.Format("Config file created by tool at {0}", Udate_time.GetCurrentDateTime())));
                //root of document
                var configuration = new XElement("configuration");
                var appSettings = new XElement("appSettings");
                foreach (var item in dict)
                {
                    if (!string.IsNullOrEmpty(item.Key))
                    {
                        appSettings.Add(new XElement("add",
                                    new XAttribute("key", item.Key),
                                    new XAttribute("value", item.Value)
                        ));
                    }
                }

                configuration.Add(appSettings);
                xmlDoc.Add(configuration);

                //create folder if not exist
                var pathStore = Path.GetDirectoryName(config_file);
                if (!Directory.Exists(pathStore))
                    Directory.CreateDirectory(pathStore);

                // Saving to a file, you can also save to streams
                xmlDoc.Save(config_file);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        // lay thong tin tu chuoi config 
        public static string GetConfig(string key , string language_code){
            if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(language_code))
            {
                //get location store file
                string file_name = string.Format(global_const.STORAGE_SETTING_FILE, language_code);
                string path = System.Web.HttpContext.Current.Server.MapPath("/" + global_const.STORAGE_FOLDER + "/" + file_name);
                // get content
                string str_ret = LoadNodeConfigSite(key, path);
                if (string.IsNullOrEmpty(str_ret))
                    str_ret = string.Format("[config_{0}]", key);
                return str_ret;
            }
            return "[config_no_key_or_lang]";
        }
    }
}
